import express, { Request, Response, Router } from 'express';
import { Op } from 'sequelize';
import UserRoomGift from '../models/sequelize/UserRoomGift';
import Gift from '../models/sequelize/Gift';
import { PaginationResponse, ApiResponse, PaginatedResponse } from '../types/SharedTypes';

const router: Router = express.Router();

// 获取礼物列表（支持分页和筛选）
router.get('/', async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      roomId,
      userId,
      giftName,
      sessionId,
      startDate,
      endDate,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;

    // 构建查询条件
    const whereClause: any = {};

    if (roomId) {
      whereClause.roomId = roomId;
    }

    if (userId) {
      whereClause.userId = userId;
    }

    // giftName查询将通过include条件处理

    if (sessionId) {
      whereClause.sessionId = sessionId;
    }

    if (startDate || endDate) {
      whereClause.createdAt = {};
      if (startDate) {
        whereClause.createdAt[Op.gte] = new Date(startDate as string);
      }
      if (endDate) {
        whereClause.createdAt[Op.lte] = new Date(endDate as string);
      }
    }

    const pageNum = parseInt(page as string, 10);
    const pageSizeNum = parseInt(pageSize as string, 10);
    const offset = (pageNum - 1) * pageSizeNum;

    // 构建include条件
    const includeConditions: any[] = [
      {
        association: 'user',
        attributes: ['id', 'name', 'avatar']
      },
      {
        association: 'room',
        attributes: ['id', 'title', 'coverUrl']
      },
      {
        model: Gift,
        as: 'gift',
        attributes: ['id', 'name', 'price', 'type', 'description', 'icon'],
        where: giftName ? {
          name: {
            [Op.like]: `%${giftName}%`
          }
        } : undefined,
        required: !!giftName // 如果有giftName条件，则必须匹配
      }
    ];

    // 查询数据
    const { count, rows } = await UserRoomGift.findAndCountAll({
      where: whereClause,
      limit: pageSizeNum,
      offset: offset,
      order: [[sortBy as string, sortOrder as string]],
      include: includeConditions
    });

    const pagination: PaginationResponse = {
      current: pageNum,
      pageSize: pageSizeNum,
      total: count,
      totalPages: Math.ceil(count / pageSizeNum)
    };

    const response: ApiResponse<PaginatedResponse<any>> = {
      success: true,
      data: {
        items: rows,
        pagination
      }
    };

    res.json(response);
  } catch (error) {
    console.error('获取礼物列表失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取礼物列表失败'  
    });
  }
});

// 根据ID获取单个礼物记录
router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const gift = await UserRoomGift.findByPk(id, {
      include: [
        {
          association: 'user',
          attributes: ['id', 'name', 'avatar']
        },
        {
          association: 'room',
          attributes: ['id', 'title', 'coverUrl']
        }
      ]
    });

    if (!gift) {
       res.status(404).json({ 
        success: false, 
        error: '礼物记录不存在' 
      });
      return
    }

    res.json({ 
      success: true, 
      data: gift 
    });
  } catch (error) {
    console.error('获取礼物记录失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取礼物记录失败' 
    });
  }
});

// 获取礼物统计信息
router.get('/stats/summary', async (req: Request, res: Response) => {
  try {
    const {
      roomId,
      userId,
      sessionId,
      startDate,
      endDate
    } = req.query;

    // 构建查询条件
    const whereClause: any = {};

    if (roomId) {
      whereClause.roomId = roomId;
    }

    if (userId) {
      whereClause.userId = userId;
    }

    if (sessionId) {
      whereClause.sessionId = sessionId;
    }

    if (startDate || endDate) {
      whereClause.createdAt = {};
      if (startDate) {
        whereClause.createdAt[Op.gte] = new Date(startDate as string);
      }
      if (endDate) {
        whereClause.createdAt[Op.lte] = new Date(endDate as string);
      }
    }

    // 获取统计数据
    const [totalGifts, totalValueResult, uniqueUsers] = await Promise.all([
      // 总礼物数量
      UserRoomGift.sum('quantity', { where: whereClause }),
      // 总礼物价值 - 通过关联查询计算
      UserRoomGift.findAll({
        where: whereClause,
        include: [{
          model: Gift,
          as: 'gift',
          attributes: ['price']
        }],
        attributes: ['quantity']
      }),
      // 独立用户数
      UserRoomGift.count({
        where: whereClause,
        distinct: true,
        col: 'userId'
      })
    ]);

    // 计算总价值
    const totalValue = totalValueResult.reduce((sum, record) => {
      const giftPrice = (record as any).gift?.price || 0;
      const quantity = record.quantity || 0;
      return sum + (giftPrice * quantity);
    }, 0);

    // 获取热门礼物排行
    const topGifts = await UserRoomGift.findAll({
      where: whereClause,
      include: [{
        model: Gift,
        as: 'gift',
        attributes: ['name', 'icon', 'price']
      }],
      attributes: [
        'giftId',
        [UserRoomGift.sequelize!.fn('SUM', UserRoomGift.sequelize!.col('quantity')), 'totalQuantity']
      ],
      group: ['giftId', 'gift.id', 'gift.name', 'gift.icon', 'gift.price'],
      order: [[UserRoomGift.sequelize!.fn('SUM', UserRoomGift.sequelize!.col('quantity')), 'DESC']],
      limit: 10
    });

    const stats = {
      totalGifts: totalGifts || 0,
      totalValue: totalValue || 0,
      uniqueUsers: uniqueUsers || 0,
      topGifts
    };

    res.json({ 
      success: true, 
      data: stats 
    });
  } catch (error) {
    console.error('获取礼物统计失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取礼物统计失败' 
    });
  }
});

// 获取用户礼物排行榜
router.get('/stats/users', async (req: Request, res: Response) => {
  try {
    const {
      roomId,
      sessionId,
      startDate,
      endDate,
      limit = 20
    } = req.query;

    // 构建查询条件
    const whereClause: any = {};

    if (roomId) {
      whereClause.roomId = roomId;
    }

    if (sessionId) {
      whereClause.sessionId = sessionId;
    }

    if (startDate || endDate) {
      whereClause.createdAt = {};
      if (startDate) {
        whereClause.createdAt[Op.gte] = new Date(startDate as string);
      }
      if (endDate) {
        whereClause.createdAt[Op.lte] = new Date(endDate as string);
      }
    }

    // 获取用户礼物排行
    const userRanking = await UserRoomGift.findAll({
      where: whereClause,
      include: [
        {
          model: Gift,
          as: 'gift',
          attributes: ['price']
        },
        {
          model: (await import('../models/sequelize/UserSnapshot')).default,
          as: 'userSnapshot',
          attributes: ['userName', 'userAvatar', 'payGrade', 'fansLevel', 'fansClubName']
        }
      ],
      attributes: [
        'userId',
        [UserRoomGift.sequelize!.fn('SUM', UserRoomGift.sequelize!.col('quantity')), 'totalGifts'],
        [UserRoomGift.sequelize!.fn('SUM', 
          UserRoomGift.sequelize!.literal('`quantity` * `gift`.`price`')
        ), 'totalValue'],
        [UserRoomGift.sequelize!.fn('COUNT', UserRoomGift.sequelize!.col('id')), 'giftCount']
      ],
      group: ['userId', 'userSnapshot.id', 'gift.id'],
      order: [[UserRoomGift.sequelize!.fn('SUM', 
        UserRoomGift.sequelize!.literal('`quantity` * `gift`.`price`')
      ), 'DESC']],
      limit: parseInt(limit as string, 10)
    });

    res.json({ 
      success: true, 
      data: userRanking 
    });
  } catch (error) {
    console.error('获取用户礼物排行失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取用户礼物排行失败' 
    });
  }
});

export default router;